package cn.com.thinvent.dispatch.web.controller;

import cn.com.thinvent.dispatch.entity.TravelManagement;
import cn.com.thinvent.dispatch.entity.request.TravelManagementRequest;
import cn.com.thinvent.dispatch.entity.response.PagedGridResult;
import cn.com.thinvent.dispatch.entity.response.ReturnModel;
import cn.com.thinvent.dispatch.service.biz.TravelManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/travel")
public class TravelManagementController {

    @Autowired
    private TravelManagementService travelManagementService;

    @PostMapping("/add")
    public ReturnModel addTravel(@RequestBody TravelManagementRequest travelManagementRequest) {
        try {
            TravelManagement savedTravel = travelManagementService.save(travelManagementRequest);
            return new ReturnModel(200, savedTravel, "添加出行管理记录成功。");
        } catch (Exception e) {
            return new ReturnModel(500, null, "添加出行管理记录失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/delete/{id}")
    public ReturnModel deleteTravel(@PathVariable String id) {
        try {
            travelManagementService.deleteById(id);
            return new ReturnModel(200, null, "删除出行管理记录成功。");
        } catch (Exception e) {
            return new ReturnModel(500, null, "删除出行管理记录失败：" + e.getMessage());
        }
    }

    @PutMapping("/update")
    public ReturnModel updateTravel(@RequestBody TravelManagementRequest travelManagementRequest) {
        try {
            TravelManagement updatedTravel = travelManagementService.update(travelManagementRequest);
            return new ReturnModel(200, updatedTravel, "更新出行管理记录成功。");
        } catch (Exception e) {
            return new ReturnModel(500, null, "更新出行管理记录失败：" + e.getMessage());
        }
    }

    @GetMapping("/get/{id}")
    public ReturnModel getTravelById(@PathVariable String id) {
        try {
            TravelManagementRequest travelManagementRequest = travelManagementService.findById(id);
            return new ReturnModel(200, travelManagementRequest, "获取出行管理记录成功。");
        } catch (Exception e) {
            return new ReturnModel(404, null, "未找到出行管理记录：" + e.getMessage());
        }
    }

    @GetMapping("/list")
    public ReturnModel getTravelList(
            @RequestParam int page,
            @RequestParam int pageSize,
            @RequestParam(required = false) String tripName,
            @RequestParam(required = false) Date startDate,
            @RequestParam(required = false) Date endDate) {
        try {
            PagedGridResult<TravelManagement> pagedResult = travelManagementService.getTravelList(page, pageSize, tripName, startDate, endDate);
            return new ReturnModel(200, pagedResult, "获取出行管理记录列表成功。");
        } catch (Exception e) {
            return new ReturnModel(500, null, "获取出行管理记录列表失败：" + e.getMessage());
        }
    }

}
